package com.cls.business.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cls.business.entity.SysSms;
import com.cls.business.mapper.SysSmsMapper;
import com.cls.business.service.ISysSmsService;
import com.cls.common.conf.SMSConfig;
import com.cls.common.entity.QueryRequest;
import com.cls.common.enums.DictEnum;
import com.cls.common.enums.SMSTemplateCodeEnum;
import com.cls.common.service.RedisService;
import com.cls.common.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 短信功能表 Service实现
 *
 * @author carey
 * @date 2020-12-17 11:07:59
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class SysSmsServiceImpl extends ServiceImpl<SysSmsMapper, SysSms> implements ISysSmsService {

    @Value("${SMS.sign-name}")
    private String signName;

    private final SMSConfig smsConfig;

    private final int okCode = 200;

    private final RedisService redisService;

    private final IAcsClient acsClient;


    @Override
    public PageInfo<SysSms> findSysSmss(QueryRequest request, SysSms sysSms) {
        LambdaQueryWrapper<SysSms> queryWrapper = new LambdaQueryWrapper<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sysSms.getSendTimeFrom()) &&
                org.apache.commons.lang3.StringUtils.equals(sysSms.getSendTimeFrom(), sysSms.getSendTimeTo())) {
            sysSms.setSendTimeFrom(sysSms.getSendTimeFrom() + " 00:00:00");
            sysSms.setSendTimeTo(sysSms.getSendTimeFrom() + " 23:59:59");
            queryWrapper.between(SysSms::getSendTime, sysSms.getSendTimeFrom(), sysSms.getSendTimeTo());
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sysSms.getSendTimeFrom())
                && org.apache.commons.lang3.StringUtils.isNotBlank(sysSms.getSendTimeFrom())) {
            queryWrapper.between(SysSms::getSendTime, sysSms.getSendTimeFrom(), sysSms.getSendTimeTo());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(sysSms.getReceiveMobile())) {
            queryWrapper.like(SysSms::getReceiveMobile, sysSms.getReceiveMobile());
        }
        if (sysSms.getSendType() != null && sysSms.getSendType()) {
            queryWrapper.eq(SysSms::getSendType, sysSms.getSendType());
        }
        queryWrapper.orderByDesc(SysSms::getSendTime);

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<SysSms> list = this.list(queryWrapper);
    /*    for (SysSms item : list) {
            if (!item.getSendType()) {
                item.setText(getAfterText(item.getTemplateCode(), item.getContentJson()));
            } else {
                item.setText(item.getContentJson());
            }
        }*/
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public List<SysSms> findSysSmss(SysSms sysSms) {
        LambdaQueryWrapper<SysSms> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createSysSms(SysSms sysSms) {
        this.save(sysSms);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysSms(SysSms sysSms) {
        this.saveOrUpdate(sysSms);
    }


    /**
     * 删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysSmss(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.removeByIds(list);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendSMS(DictEnum dictEnum, String mobile, Map<String, String> content) {
        String code = dictEnum.getCode();
        String templateCode = dictEnum.getValue();
        String jsonString = JSON.toJSONString(content);
        try {
            this.sendSmsRequest(templateCode, mobile, jsonString);
            SysSms sms = new SysSms();
            sms.setContentJson(jsonString);
            sms.setReceiveMobile(mobile);
            sms.setSendSourceType(code);
            sms.setTemplateCode(templateCode);
            sms.setSendTime(new Date());
            sms.setSendType(false);
            this.createSysSms(sms);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    public CommonResponse sendSmsRequest(String templateCode, String mobile, String jsonString) throws ClientException {
        CommonRequest request = smsConfig.getDefaultPostCommonRequest();
        System.err.println(acsClient.hashCode());
        System.err.println(request);
        IAcsClient client2 = smsConfig.getAcsClient();
        System.err.println(client2.hashCode());
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", jsonString);
        return acsClient.getCommonResponse(request);
    }

    public CommonResponse sendQuerySmsTemplateRequest(String templateCode) throws ClientException {
        IAcsClient client = smsConfig.getAcsClient();
        CommonRequest request = smsConfig.getDefaultPostCommonRequest();
        request.setSysAction("QuerySmsTemplate");
        request.putQueryParameter("TemplateCode", templateCode);
        return client.getCommonResponse(request);
    }

    public String getTemplateFromRedis(String templateCode) throws ClientException {
        Object templateObj = redisService.get(templateCode);
        if (Objects.isNull(templateObj)) {
            CommonResponse response = sendQuerySmsTemplateRequest(templateCode);
            if (response.getHttpStatus() == okCode) {
                String responseDate = response.getData();
                HashMap map = JSONUtil.toBean(responseDate, HashMap.class);
                templateObj = map.get("TemplateContent").toString();
                redisService.set(templateCode, templateObj.toString());
            }
        }
        return templateObj.toString();
    }

    public String getAfterText(String templateCode, String json) {
        String template = SMSTemplateCodeEnum.getByCode(templateCode);
        HashMap map = JSONUtil.toBean(json, HashMap.class);
        String result = StringUtils.processTemplate(template, map);
        return result;
    }


    public CommonResponse sendQuerySendDetailsRequest(String phone, Date sendDate, String pageSize, String currentPage) throws ClientException {
        IAcsClient client = smsConfig.getAcsClient();
        CommonRequest request = smsConfig.getDefaultPostCommonRequest();
        String sendDateStr = DateUtil.format(sendDate, DatePattern.PURE_DATE_PATTERN);
        request.setSysAction("QuerySendDetails");
        request.putQueryParameter("PhoneNumber", phone);
        request.putQueryParameter("SendDate", sendDateStr);
        request.putQueryParameter("PageSize", pageSize);
        request.putQueryParameter("CurrentPage", currentPage);
        return client.getCommonResponse(request);
    }
}
